<!--
  - Copyright (c) 2019.  武汉中科图灵科技有限公司
  - Date :  2019/1/5
  - Author ：F12 Console=> atob("MzMxNDkxODAwQHFxLmNvbQ==")
  - Version ：1.6.2
  -->

<template>
  <div><div class="abstatic-height"></div>
  <div class="app-container calendar-list-container">
    <el-container>
      <div class="flex-left-pannel flex-left-pannel__noright">
        <el-row>
          <div class="xf-tabletop-handles">
            <div class="xf-tabhd-left">
              <el-button class="filter-item" @click="handleCreate" type="primary" size="mini">添加巡检计划</el-button>
            </div>
            <div class="xf-tabhd-right">
              路线名
              <el-input v-model="listQuery.routeName" placeholder="请输入路线名" clearable class="xf-query-input" size="mini"></el-input>
              <el-button @click="tableQuery" type="primary" size="mini">查询</el-button>
              <el-popover
                placement="bottom-end"
                width="375"
                class="xf-custom-poper"
                v-model="visible2">
                <div class="xf-double-form">
                  <div class="xf-dbform-item">
                    <div class="xf-dbform-item__sleft">
                      <p class="xf-dbform-item__label">开始日期</p>
                      <el-date-picker
                        v-model="slistQuery.startTime"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        start-placeholder="开始"
                        end-placeholder="结束"
                        placeholder="选择开始日期">
                      </el-date-picker>
                    </div>
                  </div>
                  <div class="xf-dbform-item">
                    <div class="xf-dbform-item__sleft">
                      <p class="xf-dbform-item__label">结束日期</p>
                      <el-date-picker
                        v-model="slistQuery.endTime"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        start-placeholder="开始"
                        end-placeholder="结束"
                        placeholder="选择结束日期">
                      </el-date-picker>
                    </div>
                  </div>
                  <div class="xf-dbform-item">
                    <div class="xf-dbform-item__sleft" style="width: 100%;">
                      <p class="xf-dbform-item__label">巡检周期</p>
                      <el-input v-model="slistQuery.patrolCycle	" placeholder="请输入巡检周期" style="width: 100%;">
                        <span slot="append">天</span>
                      </el-input>
                    </div>
                  </div>
                </div>
                <div style="text-align: left; margin: 0; margin-top:20px;">
                  <el-button size="mini" type="primary" @click="pointerQuery">查询</el-button>
                  <el-button type="text" @click="visible2 = false">取消</el-button>
                </div>
                <el-button slot="reference" type="text" size="mini">高级查询</el-button>
              </el-popover>
            </div>
          </div>
        </el-row>
        <el-table
          key='tableKey'
          :data="list"
          ref="multipleTable"
          v-loading.body="listLoading" fit style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column label="路线名">
            <template slot-scope="scope">
              <span>{{scope.row.routeName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="开始日期">
            <template slot-scope="scope">
              <span>{{scope.row.startTime}}</span>
            </template>
          </el-table-column>
          <el-table-column label="结束日期">
            <template slot-scope="scope">
              <span>{{scope.row.endTime}}</span>
            </template>
          </el-table-column>
          <el-table-column label="巡检周期">
            <template slot-scope="scope">
              <span>{{scope.row.patrolCycle}}天</span>
            </template>
          </el-table-column>
          <el-table-column label="巡检时段">
            <template slot-scope="scope">
              <span>{{scope.row.timeCount}}个</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="130" fixed="right">
            <template slot-scope="scope">
              <span @click="handleUpdate(scope.row)" class="comm-table-btn"><icon-svg icon-class="bianji" style="fill:#50E3C2" /></span>
              <span @click="createDel(scope.row)" class="comm-table-btn"><icon-svg icon-class="shanchu" style="fill:#50E3C2" /></span>
            </template>
          </el-table-column>
        </el-table>
        <div v-show="!listLoading" class="sensor-pagination-container">
          <div>
            <el-checkbox v-model="isselall" :indeterminate="isIndeterminate" @change="handleCheckAllChange" v-show="list&&list.length!=0">全选</el-checkbox>
            <el-button type="text" style="margin-left: 10px;" @click="delAllSensor" v-show="list&&list.length!=0" :disabled="checklist&&checklist.length==0">全部删除</el-button>
          </div>
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,15,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
        </div>
      </div>
    </el-container>
    <slider-panel :Show.sync="dialogFormVisible" custom-class="out-side-frame">
      <div class="form-content-frame">
        <el-form :model="patrolForm" ref="addpatrolForm" :rules="rules" label-width="100px" label-position='top' @submit.native.prevent>
          <el-form-item label="路线名" prop="inspectionRouteId">
            <el-select v-model="patrolForm.inspectionRouteId" placeholder="请选择路线" style="width: 100%">
              <el-option :label="item.routeName" :value="item.id" v-for="(item,index) in routeList" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开始日期" prop="startTime">
            <el-date-picker
              v-model="patrolForm.startTime"
              type="date"
              :editable="false"
              value-format="yyyy-MM-dd"
              placeholder="请选择开始日期" style="width: 100%">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束日期（为空表示用不结束）" prop="endTime">
            <el-date-picker
              v-model="patrolForm.endTime"
              type="date"
              :editable="false"
              value-format="yyyy-MM-dd"
              placeholder="请选择结束日期" style="width: 100%">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="巡检周期" prop="patrolCycle">
            <el-input v-model.Number="patrolForm.patrolCycle  " placeholder="请输入巡检周期" style="width: 100%;">
              <span slot="append">天</span>
            </el-input>
          </el-form-item>
          <el-form-item
            v-for="(times, index) in patrolForm.timePeriod"
            :label="'巡检时段' + (index+1)"
            :key="index"
            :prop="'timePeriod.' + index + '.value'"
            :rules="rules.value"
          >
            <el-time-picker
              is-range
              v-model="times.value"
              :editable="false"
              start-placeholder="巡检开始时间"
              end-placeholder="巡检结束时间"
              value-format="HH:mm"
              format="HH:mm"
              placeholder="选择时间范围" style="width: 95%">
            </el-time-picker>
            <el-button icon="el-icon-remove-outline" type="text" @click.prevent="removeInputs(times)"></el-button>
          </el-form-item>
          <div class="timeadd-btnbox" style="text-align: right">
            <el-button @click.prevent="addInput()" type="text">+添加巡检时段</el-button>
          </div>
            <el-button v-if="dialogStatus==='create'" type="primary" @click="create('addpatrolForm')" size="mini" native-type="submit">确 定</el-button>
            <el-button v-else type="primary" @click="update('addpatrolForm')" size="mini" native-type="submit">确 定</el-button>
            <el-button @click="cancel('addpatrolForm')" size="mini" type="text">取 消</el-button>
        </el-form>
      </div>
    </slider-panel>
    <el-dialog title="删除巡检计划" :visible.sync="dialogDeleteVisible" :show-close='false' custom-class="xf-jc-dialog" width="360px">
      <div class="xf-jc-deletect">
        <p>确定删除巡检计划吗？</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" size="mini" @click="deleteD()">删除</el-button>
        <el-button type="text" size="mini" @click="dialogDeleteVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
  </div>
</template>
<script>
  import {
    page,
    addQuery,
    addObj,
    updateObj,
    deleteObj
  } from "@/api/device/patrolScheme/index";

  import {validatInter} from '@/utils/validate';
  import sliderPanel from '@/components/SliderPanel'

  export default {
    name: "patrolScheme",
    components: {sliderPanel},
    data() {
      const validateInterg = (rule, value, callback) => {
        if (!validatInter(value)&&value.length<=3) {
          callback(new Error("请输入大于0小于3位的整数"));
        } else {
          callback();
        }
      };
      var validateEnd = (rule, value, callback) => {
        setTimeout(() => {
          let cdate = new Date(String(value)).getTime();
          let prdate = new Date(String(this.patrolForm.startTime)).getTime();
          if (cdate&&(cdate<prdate)) {
            callback(new Error('结束日期不能早于开始日期'))
          } else {
            callback()
          }
        }, 1000)
      };
      return {
        currentId:'',
        delsensorid:[],
        isselall:false,
        isIndeterminate:false,
        checklist:[],
        visible2: false,
        routeList:[],
        patrolForm: {
          inspectionRouteId:'',
          startTime:'',
          endTime:'',
          patrolCycle:'',
          timePeriod:[{value:''}]
        },
        rules: {
          inspectionRouteId: [
            {
              required: true,
              message: "请选择路线",
              trigger: "change"
            }
          ],
          startTime: [
            {
              required: true,
              message: "请选择开始日期",
              trigger: "change"
            }
          ],
          endTime:[
            {
              required: false,
              validator: validateEnd,
              trigger: "change"
            }
          ],
          value:[{
            required: true,
            message: '时段不能为空',
            trigger: 'change'
          }],
          patrolCycle:[
            {
              required: true,
              validator: validateInterg,
              trigger: "blur"
            }
          ]
        },
        list: null,
        total: null,
        listLoading: true,
        slistQuery: {
          patrolCycle:'',
          startTime:'',
          endTime:'',
        },
        listQuery: {
          page: 1,
          limit: 15,
          routeName: ""
        },
        dialogFormVisible: false,
        dialogFormChildVisible: false,
        dialogDeleteVisible: false,
        dialogStatus: "",
        textMap: {
          update: "编辑巡检计划",
          create: "添加巡检计划"
        },
        tableKey: 0,
        currentSelectObj: {}
      };
    },
    created() {
      this.getList();
    },
    methods: {
      handleSelectionChange(val){
        this.checklist=[...val];
        let length = this.total>this.list.length?this.list.length:this.total;
        if (val.length===length) {
          this.isselall=true;
          this.isIndeterminate=false;
        }else{
          this.isselall=false;
          this.isIndeterminate=true;
        }
        if (val.length===0) {
          this.isIndeterminate=false;
        }
      },
      removeInputs(times){
        if (this.patrolForm.timePeriod.length>1) {
          var index = this.patrolForm.timePeriod.indexOf(times);
          if (index !== -1) {
            this.patrolForm.timePeriod.splice(index, 1)
          }
        }else {
          this.$message({
            message: '至少选择一个巡检时段',
            type: 'warning'
          });
        }
      },
      addInput(){
        this.patrolForm.timePeriod.push({
          value: '',
        });
      },
      delAllSensor(){
        this.delsensorid=[];
        this.checklist.forEach((item,index)=>{
          this.delsensorid.push(item.id);
        });
        this.dialogDeleteVisible=true;
      },
      handleCheckAllChange(){
        this.$refs.multipleTable.toggleAllSelection();
      },
      createDel(row){
        this.delsensorid=[];
        this.delsensorid.push(row.id);
        this.dialogDeleteVisible=true;
      },
      deleteD(){
        this.dialogDeleteVisible = false;
        deleteObj({ids:(this.delsensorid).toString()}).then(() => {
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 2000
          });
          this.listQuery.page = 1;
          this.getList();
        });
      },
      tableQuery() {
        this.restPoinrterQuery();
        this.getList();
      },
      pointerQuery() {
        // 高级查询
        this.visible2 = false;
        this.listLoading = true;
        // 取消绑定并合并查询条件
        let contactKeys = Object.assign(
          {},
          JSON.parse(JSON.stringify(this.listQuery)),
          {
            patrolCycle:this.slistQuery.patrolCycle,
            startTime: String(this.slistQuery.startTime),
            endTime: String(this.slistQuery.endTime)
          }
        );
        page(contactKeys).then(response => {
          this.list = response.data.rows;
          this.total = response.data.total;
          this.listLoading = false;
        });
      },
      handleCreate() {
        this.dialogStatus = "create";
        this.handlerest();
        this.dialogFormVisible = true;
        addQuery().then(res=>{
          this.routeList = res.data.routes;
        });
      },
      restPoinrterQuery(){
        this.slistQuery.patrolCycle = '';
        this.slistQuery.startTime = '';
        this.slistQuery.endTime = '';
      },
      handlerest() {
         this.patrolForm.inspectionRouteId = '';
         this.patrolForm.startTime = '';
         this.patrolForm.endTime = '';
         this.patrolForm.patrolCycle = '';
         this.patrolForm.timePeriod = [{value:''}];
      },
      handleUpdate(row) {
        this.currentId = row.id;
        addQuery({ id: row.id})
          .then(res => {
            this.routeList = res.data.routes;
            this.patrolForm.inspectionRouteId = res.data.inspectionScheme.inspectionRouteId;
            this.patrolForm.startTime = res.data.inspectionScheme.startTime;
            this.patrolForm.endTime = res.data.inspectionScheme.endTime;
            this.patrolForm.patrolCycle = res.data.inspectionScheme.patrolCycle;
            let temparr = [];
            res.data.times.forEach(item=>{temparr.push({
              value:item
            })});
            this.patrolForm.timePeriod = temparr;
            this.dialogFormVisible = true;
            this.dialogStatus = "update";
          })
          .catch(function(error) {
            console.log(error);
          });
      },
      create(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            let temarr = [];
            this.patrolForm.timePeriod.forEach(item=>{temarr.push(item.value)});
            this.patrolForm.timePeriod = temarr;
            addObj(this.patrolForm).then((res) => {
              if (res.status===200){
                this.dialogFormVisible = false;
                this.getList();
                this.$notify({
                  title: "成功",
                  message: "添加成功",
                  type: "success",
                  duration: 2000
                });
                this.$refs[formName].resetFields();
                this.handlerest();
              }
            });
          } else {
            return false;
          }
        });
      },
      update(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            let temarr = [];
            this.patrolForm.timePeriod.forEach(item=>{temarr.push(item.value)});
            this.patrolForm.timePeriod = temarr;
            updateObj(Object.assign({},{id:this.currentId},this.patrolForm) )
              .then((res) => {
                if (res.status===200){
                  this.dialogFormVisible = false;

                  this.$refs[formName].resetFields();
                  this.handlerest();
                  this.getList();
                  this.$notify({
                    title: "成功",
                    message: "修改成功",
                    type: "success",
                    duration: 2000
                  });
                }
              })
              .catch(function(error) {
                console.log(error);
              });
          } else {
            return false;
          }
        });
      },
      cancel(formName) {
        this.dialogFormVisible = false;

        this.handlerest();
        this.$refs[formName].resetFields();
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      getList() {
        this.listLoading = true;
        this.isselall  = false;
        this.isIndeterminate = false;
        let contactKeys = Object.assign(
          {},
          JSON.parse(JSON.stringify(this.listQuery)),
          {
            patrolCycle:this.slistQuery.patrolCycle,
            startTime: String(this.slistQuery.startTime),
            endTime: String(this.slistQuery.endTime)
          }
        );
        page(contactKeys).then(res => {
          this.list = res.data.rows;
          this.total = res.data.total;
          this.listLoading = false;
        });
      }
    },
    mounted() {

    },
  };
</script>
<style rel="stylesheet/scss" lang="scss">
  .sensor-pagination-container{
    display:flex;
    justify-content:space-between;
    padding:10px 10px;
  }
  .el-time-spinner{
    box-sizing: content-box;
  }
  .flex-left-pannel__noright {
    padding-right: 0;
  }
  .xf-input-withbtn__rightbtn {
    border: 0;
    height: 34px;
    margin-top: -8px !important;
  }
  .fulldialog > div {
    width: 500px;
    margin: 0 auto;
  }
  .fulldialog .el-dialog__title {
    font-size: 32px;
  }
  .device-add-dialog {
    .el-dialog__title {
      font-size: 32px;
    }
    .el-dialog__header {
      margin-top: 20px;
    }
    .custom-dialog-btn {
      position: absolute;
      font-size: 30px;
      left: 40px;
      top: 20px;
      color: #fff;
      &:hover {
        cursor: pointer;
      }
    }
    .dialog-footer {
      text-align: left;
    }
  }
  // 精准查询
  .xf-double-form{
    .xf-dbform-item{
      display: flex;
      justify-content: space-between;
      .xf-dbform-item__sleft{
        .el-input{
          width: 320px;
        }
      }
      .xf-dbform-item__sright{
        .el-input{
          width: 320px;
        }
      }
    }
  }
</style>
